<template>
	<a-spin :loading="loading" :tip="$t('base.loading')" class="detail-aside">
		<div class="customer-top">
			<a-avatar :style="{ backgroundColor: '#e8f3ff', color: '#031a79' }" :size="48">{{ customerInfo?.key?.labelShort }}</a-avatar>
			<h2>{{ customerInfo?.key?.parm }}</h2>
			<p>{{ $t("customer.create") }}{{ getDateDiff(customerInfo?.createTime) }}</p>
		</div>
		<div ref="target">
			<div v-for="(item, index) in fieldList" :key="item.id">
				<a-form :model="item" ref="formRef"  v-if="item?.columns?.length" class="list-item">
					<ComTitle v-if="item.name && index != 0" :title2="item.name || ''" style="line-height: 24px; padding: 0" />
					<div class="field-box">
						<a-form-item
							validate-trigger="change"
							style="margin-bottom: 0"
							v-for="(child, childIndex) in item.columns"
							asterisk-position="start"
							hide-label
							:field="`columns[${childIndex}].fieldValue`"
							:rules="{ required: child.isRequired, message: $t('base.placeholder') + child?.name }"
						>
							<component
							size="mini"
								@click="activeEdit = child.id"
								:name="child.prop?.name"
								:icon="child.prop?.ico"
								style="padding: 4px 10px; min-height: 36px; width: 100%; cursor: pointer"
								:arcoProps="{
									'checked-value': '1',
									'unchecked-value': '0'
								}"
								v-model="child.fieldValue"
								v-model:fieldShow="child.fieldShow"
								v-model:extra="child.extra"
								:options="child?.options"
								:tag="SelectInfo(showFieldList, child?.fieldType, 'tag')"
								:prop="child.prop"
								:fieldType="SelectInfo(showFieldList, child?.fieldType, 'fieldType')"
								:status="activeEdit === child.id ? 'edit' : 'view'"
								:is="SelectInfo(showFieldList, child?.fieldType, 'component')"
								labelWidth="100px"
								@change="saveData"
								@outClick="activeEdit = ''"
							></component>
						</a-form-item>
					</div>
				</a-form>
			</div>
		</div>
	</a-spin>
</template>
<script lang="ts" setup>
import { SelectInfo } from "@/utils/index";
import { columnConfig, customerDataUpdate, customerDataInfo } from "@/api/customerManage/customer";
import ComTitle from "@/components/ComTitle.vue";
import { useI18n } from "@/hooks/useI18n";
import { getDateDiff } from "@/utils/index";
import { useShowFieldList } from "@/utils/field";
const showFieldList = useShowFieldList();
const emit = defineEmits(["update"]);
const { t } = useI18n();
const target = ref({});

const message = useMessage();

const props = defineProps({
	bizId: {
		type: String,
		default: ""
	},
	customerId: {
		type: String,
		default: ""
	}
});

const activeEdit = ref("");

const formRef = ref(null);
const saveLoading = ref(false);
const saveData = async () => {
	if (formRef.value) {
		const flag = formRef.value.map(async (i) => await i.validate());

		const res = await Promise.all(flag);
		const bool = res.some((i) => i);
		if (bool) return;
	}
	try {
		saveLoading.value = true;
		const arr = mergeColumns(fieldList.value);
		const obj = arr.map((i) => {
			return {
				fieldConfig: i.id,
				fieldShow: i.fieldShow,
				fieldValue: i.fieldValue,
				id: i.columnId,
				extra: i.extra ? JSON.stringify(i.extra) : null
			};
		});
		await customerDataUpdate({
			bizId: props.bizId,
			mainId: props.customerId,
			columnList: obj
		});
		message.success(t("base.saveSuccess"));
		await getCustomerInfo();
		emit("update");
	} catch (error) {
	} finally {
		saveLoading.value = false;
	}
	// close();
};

// 把columns取出来合并到一起
function mergeColumns(arr: any[]): any[] {
	const result: any[] = [];
	arr.forEach((item) => {
		if (item.columns && Array.isArray(item.columns)) {
			result.push(...item.columns);
		}
	});
	return result;
}
const loading = ref(false);
const fieldList = ref([]);
const getColumn = async () => {
	const data = await columnConfig({
		bizId: props.bizId
	});
	data.forEach((i) => {
		if (Array.isArray(i.columns)) {
			i.columns.forEach((j) => {
				j.prop = getProp(j);
				j.options = getOptions(j)
				const info = customerInfo.value[j.id];
				if (info) {
					j.fieldValue = info?.value;
					j.fieldShow = info?.parm;
					j.columnId = info?.columnId;
				}
				j.extra = info?.extraObject || j.extraObject;
			});
		}
	});
	fieldList.value = data;
};
const getOptions = (item)=>{
	if ([5, 6].includes(item.fieldType)) {
		return item.values;
	} 
}
const getProp = (item) => {
	let obj = {
		ico: item.ico,
		name: item.name
	};
	if ([5, 6].includes(item.fieldType)) {
		obj = { ...obj, options: item.values };
	} else {
		obj = { ...obj, ...item.extraObject };
	}
	return obj;
};
const customerInfo = ref({});
const getCustomerInfo = async () => {
	try {
		loading.value = true;

		const data = await customerDataInfo({
			mainId: props.customerId
		});
		customerInfo.value = data;
		await getColumn();
	} catch (error) {
	} finally {
		loading.value = false;
	}
};

// const handleChange = (data, child) => {
// 	if (!data) return;
// 	if ([5, 6].includes(child.fieldType)) {
// 		//单选多选
// 		child.fieldShow = data.map((i) => i.parm).join(",");
// 	}
// };

watch(
	() => props.customerId,
	async (data) => {
		if (data) {
			await getCustomerInfo();
		}
	},
	{ immediate: true }
);

defineExpose({
	saveData,
	saveLoading
});
</script>

<style scoped lang="scss">
.detail-aside {
	width: 410px;
	border-right: 1px solid #ebebeb;
	.customer-top {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 24px 24px 12px 24px;
		line-height: 1;
		h2 {
			font-size: 18px;
			color: #333;
			margin-top: 10px;
		}
		p {
			margin-top: 10px;
			font-size: 12px;
			color: #c9cdd4;
		}
	}
	.list-item {
		border-top: 1px solid #f2f2f2;
		padding: 10px;
	}
}
</style>
